/**
 * feed base info
 */
define(['../../common/service',  '../../model/currency',  './feed'],
    function (http,  currency, feed) {
        var ProductPreview = {
            init: function () {
                var _this = this;

                feed._init_tabs(1);
                var feedId = window.localStorage.getItem('weFeedId');
                if (feedId) {
                    //货币下拉框
                    _this.showCurreny();
                    //调度
                    _this.showInterval();
                    _this.preview_btn_event();
                    _this.show_baseInfo(feedId);

                    if(window.sessionStorage.roleId.indexOf(1) > -1) {
                        var addBtnDom = $('.feed-urls .add-btn');
                        addBtnDom.removeClass('hidden');
                        $(".btn[name='update-btn']").removeClass('hidden');
                        $("input[name=feedName]").removeAttr("disabled");
                        $("input[name=promotedWebsite]").removeAttr("disabled");
                        $("input[name=feedUrl]").removeAttr("disabled");
                        $("input[name=utmSource]").removeAttr("disabled");
                        $("input[name=utmMedium]").removeAttr("disabled");
                        $("input[name=utmTerm]").removeAttr("disabled");
                        $("input[name=utmContent]").removeAttr("disabled");
                        $("input[name=utmCampaign]").removeAttr("disabled");
                        $("input[name=utmCustom]").removeAttr("disabled");

                        _this.validateFeedName(feedId);
                        //绑定事件
                        _this.add_btn_event(addBtnDom);
                        _this.remove_btn_event($('.feed-urls  .remove-btn'));
                        _this.modify_btn_event(feedId);
                    }
                }
            }
            , add_btn_event: function ($Dom) {
                var self = this;
                var node = '<div class="feed-urls-wrapper"><input type="text" name="feedUrl" placeholder="'+I18N.getText('feedList', 'pleaseInputFeedUrl')+'" class="form-input"/>'
                    + '<button type="button" class="close" data-dismiss="alert" aria-label="Close" ><span aria-hidden="true"'
                    + ' style="font-size: 27px;">&times;</span></button></div>';
                $Dom.unbind("click").bind("click", function (e) {
                    var $Dom = $(this).parent().append(node);
                    var _removeD = $Dom.find(".close");
                    $(this).parent().find(".close").removeClass("hidden");
                    self.remove_btn_event(_removeD);
                    return false;
                });
            }
            , remove_btn_event: function ($Dom) {
                $Dom.unbind("click").on("click", function (e) {
                    var _parentWrapper = $(this).parent();
                    var _brothers = _parentWrapper.siblings("div").length;
                    if (1 == _brothers) {
                        //最后一个不能删除
                        _parentWrapper.parent().find("button.close").addClass("hidden");
                    }
                    _parentWrapper.remove();
                    return false;
                });
            }
            /**
             * 修改基本信息
             */
            , modify_btn_event:function(feedId){
                var self = this;
                $(".btn[name='update-btn']").click(function(){
                    //检查字符
                    if(!self.check_form_value()){
                        return false;
                    }
                    var feedUrls ={
                        urls : []
                    };
                    $("input[name=feedUrl]").each(function(i,obj){
                        if(!Kit.isBlank($(obj).val()))
                            feedUrls.urls.push($(obj).val());
                    });
                    var param = {
                        feedName: $.trim($("input[name=feedName]").val()),
                        promotedWebsite:$.trim($("input[name=promotedWebsite]").val()),
                        currency:$("select[name=currency]").val(),
                        interval:$("input[name=interval]").data('val'),
                        hour:$("input[name=hour]").data('val'),
                        originUrls:feedUrls,
                        utmSource:$("input[name=utmSource]").val(),
                        utmMedium:$("input[name=utmMedium]").val(),
                        utmTerm:$("input[name=utmTerm]").val(),
                        utmContent:$("input[name=utmContent]").val(),
                        utmCampaign:$("input[name=utmCampaign]").val(),
                        utmCustom:$("input[name=utmCustom]").val(),
                        id:feedId
                    }
                    if($("input[name=interval]").data('val') == 'WEEKLY')
                        param.dayOfWeek = $("input[name=dayOfWeek]").data('val');
                    http.work('/feed/update ',param,'POST').then(function(res) {
                        if (res.flag == "fail") {
                            Kit.alert2(res.errorMsg);
                            return;
                        }else{
                            Kit.alert_success(I18N.getText('feedUpdate', 'updateSuccess'));
                        }
                    });
                    return false;
                });
            }
            /**
             * 跳转到productPreview 页面
             */
            , preview_btn_event:function(){
                $(".btn[name='preview-btn']").click(function(){
                    window.location.hash = "#!productPreview";
                    return false;
                });
            }
            , check_form_value:function(){
                var flag = true;
                //feed名称不能为空
                if (Kit.isBlank($("input[name=feedName]").val())){
                    Kit.alert2(I18N.getText('feedList','enterFeedName'));
                    return false;
                }
                //推广网址 不能为空
                if (Kit.isBlank($("input[name=promotedWebsite]").val())){
                    Kit.alert2(I18N.getText('feedList','enterPromotedWebsite'));
                    return false;
                }
                //货币必选
                var currencyVal = $("select[name=currency]").val();
                if (Kit.isBlank(currencyVal) || currencyVal == '-1'){
                    Kit.alert2(I18N.getText('feedList','setCurrency'));
                    return false;
                }
                //feedUrl不能为空
                var urlInputNull = false;
                $('input.urlInput').each(function(k){
                    if(Kit.isBlank($(this).val())){
                        Kit.alert2(I18N.getText('feedList','enterFeedUrl', k+1));
                        $(this).focus();
                        urlInputNull = true;
                    }
                })
                if(urlInputNull)
                    return false;
                return flag;
            }
            /**
             * feed名称重名校验
             */
            ,validateFeedName:function(feedId){
                $('input[name=feedName]').change(function(){
                    var _thisName = $(this);
                    var nameV = $.trim(_thisName.val());
                    if(Kit.isBlank(nameV))
                        return;
                    var paramFeedName = {
                        feedName : nameV,
                        id : feedId
                    }
                    http.work('/feed/validate',paramFeedName,'POST').then(function(res){
                        if (res.succeed){
                            if(res.data == 2) {
                                Kit.alert2(I18N.getText('feedList','feedNameRepeat'));
                                _thisName.addClass("form-input-warning");
                                _thisName.val("").focus();
                            } else if(res.data == 1) {
                                _thisName.removeClass("form-input-warning");
                            }
                        } else {
                            Kit.alert2(res.errorMsg);
                            return false;
                        }
                    });
                });
            }
            /**
             *  货币
             */
            , showCurreny:function(){
                var _this = this;
                var cur = currency[I18N.language];
                var curHtml = '<option value="-1">' + I18N.getText('feedList', 'setCurrency') + '</option>';
                for(var c = 0; c< cur.length; c++){
                    curHtml += '<option value="'+cur[c].unit+'">&nbsp;' +cur[c].unit+ '--' + cur[c].name + '</option>';
                }
                var curSelect = $("select[name=currency]");
                curSelect.empty();
                curSelect.html(curHtml);
                curSelect.select2();
            }
            /**
             * 调度
             * @param feedId
             */
            , showInterval:function(){
                var _this = this;
                var dayOfWeekDiv = $("div.ndp-drop-wrapper[name=dayOfWeek-drop]");
                var dayOfWeekSymbol = $("span[name=dayOfWeek-symbol]");
                //调度
                $("div.ndp-drop-wrapper[name=interval-drop]").empty().drop({
                    data:[{
                        value: 'DAILY',
                        text: I18N.getText('feedList', 'daily')
                    }],
                    name:"interval"
                }).off("ITEM_CLICK").on("ITEM_CLICK",function(e){
                    var val = e.originalEvent.data.val;
                    if('DAILY' == val) {
                        dayOfWeekDiv.addClass('hidden');
                        dayOfWeekSymbol.addClass('hidden');
                    } else if ('WEEKLY' == val) {
                        dayOfWeekDiv.removeClass('hidden');
                        dayOfWeekSymbol.removeClass('hidden');
                        dayOfWeekDiv.empty().drop({
                            data:[{
                                value: 'MONDAY',
                                text: I18N.getText('feedList', 'monday')
                            },{
                                value: 'TUESDAY',
                                text: I18N.getText('feedList', 'tuesday')
                            },{
                                value: 'WEDNESDAY',
                                text: I18N.getText('feedList', 'wednesday')
                            },{
                                value: 'THURSDAY',
                                text: I18N.getText('feedList', 'thursday')
                            },{
                                value: 'FRIDAY',
                                text: I18N.getText('feedList', 'friday')
                            },{
                                value: 'SATURDAY',
                                text: I18N.getText('feedList', 'saturday')
                            },{
                                value: 'SUNDAY',
                                text: I18N.getText('feedList', 'sunday')
                            }],
                            name:"dayOfWeek"
                        }).off("ITEM_CLICK").on("ITEM_CLICK",function(e){
                            //console.log(e.originalEvent.data);
                        }).val({
                            value: 'MONDAY',
                            text: I18N.getText('feedList', 'monday')
                        });
                    }
                }).val({
                    value: 'DAILY',
                    text: I18N.getText('feedList', 'daily')
                });

                $("div.ndp-drop-wrapper[name=hour-drop]").empty().drop({
                    data: _this.getHour(),
                    name:"hour"
                }).off("ITEM_CLICK").on("ITEM_CLICK",function(e){
                    //console.log(e.originalEvent.data);
                }).val({
                    value: '0',
                    text: '00:00'
                });
            }
            /**
             * 显示 feed 的基本信息
             */
            , show_baseInfo:function(feedId){
                http.do('/feed/getFeed ',{feedId:feedId},'GET').then(function(res) {
                    if (res.flag == "fail") {
                        Kit.alert2(res.errorMsg);
                        return;
                    }else{
                        var _data = res.data;
                        $("input[name=feedName]").val(_data.feedName);
                        $("input[name=promotedWebsite]").val(_data.promotedWebsite);
                        $('select[name=currency] option[value="'+_data.currency+'"]').attr('selected', true);
                        $('select[name=currency]').select2();
                        $('div[name=interval-drop] .drop-list .drop-one-item[value="'+ _data.interval +'"]').trigger('click');
                        if(_data.dayOfWeek)
                            $('div[name=dayOfWeek-drop] .drop-list .drop-one-item[value="'+ _data.dayOfWeek +'"]').trigger('click');
                        $('div[name=hour-drop] .drop-list .drop-one-item[value="'+ _data.hour +'"]').trigger('click');
                        $("input[name=utmSource]").val(_data.utmSource);
                        $("input[name=utmMedium]").val(_data.utmMedium);
                        $("input[name=utmTerm]").val(_data.utmTerm);
                        $("input[name=utmContent]").val(_data.utmContent);
                        $("input[name=utmCampaign]").val(_data.utmCampaign);
                        $("input[name=utmCustom]").val(_data.utmCustom);
                        //_data.feedUrl String
                        var tempObj = JSON.parse(_data.originUrls + "");
                        $.each(tempObj.urls,function(i,obj){
                            //添加 urls
                            if(i>0){
                                $('.feed-urls .add-btn').click();
                            }
                            $("input[name=feedUrl]").eq(i).val(obj);
                        });
                    }
                });
            }
            /*
             @时间静态数据
             * */
            ,getHour: function(){
                var operatingSystem = [{
                    value: '0',
                    text: '00:00'
                },{
                    value: 1,
                    text: '01:00'
                },{
                    value: 2,
                    text: '02:00'
                },{
                    value: 3,
                    text: '03:00'
                },{
                    value: 4,
                    text: '04:00'
                },{
                    value: 5,
                    text: '05:00'
                },{
                    value: 6,
                    text: '06:00'
                },{
                    value: 7,
                    text: '07:00'
                },{
                    value: 8,
                    text: '08:00'
                },{
                    value: 9,
                    text: '09:00'
                },{
                    value: 10,
                    text: '10:00'
                },{
                    value: 11,
                    text: '11:00'
                },{
                    value: 12,
                    text: '12:00'
                },{
                    value: 13,
                    text: '13:00'
                },{
                    value: 14,
                    text: '14:00'
                },{
                    value: 15,
                    text: '15:00'
                },{
                    value: 16,
                    text: '16:00'
                },{
                    value: 17,
                    text: '17:00'
                },{
                    value: 18,
                    text: '18:00'
                },{
                    value: 19,
                    text: '19:00'
                },{
                    value: 20,
                    text: '20:00'
                },{
                    value: 21,
                    text: '21:00'
                },{
                    value: 22,
                    text: '22:00'
                },{
                    value: 23,
                    text: '23:00'
                }];
                return operatingSystem;
            }
        }
        return ProductPreview;
    });
